﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Configuration;
using Gollie.Mail;

namespace Gollie.Payment.Targetpay
{
	public class BankWireHandler : PaymentHandler
	{
		public BankWireHandler(string transactionId, string rtlo, string amountdue, string amountpaid, string checksum)
			: base(transactionId, true)
		{
			logger.Info("Bankwire report handler: Handling TargetPay wire payment...");

			this.Kenmerk = transactionId;
			this.Rtlo = rtlo;
			this.AmountDue = amountdue;
			this.AmountPaid = amountpaid;
			this.Checksum = checksum;

			logger.Info("Bankwire report: trxid: {0}, amountdue: {1}, amountpaid {2}, checksum {3}", transactionId, amountdue, amountpaid, checksum);
		}

		protected override bool IsPayedConfirmed()
		{
			StringBuilder hasher = new StringBuilder(64);

			hasher.Append(Kenmerk);
			hasher.Append(Rtlo);
			hasher.Append(AmountDue);
			hasher.Append(AmountPaid);
			hasher.Append(ConfigAppSettings.GetValue("wiresalt"));

			string mychecksum = Hash.GetMD5Hash(hasher.ToString());

			bool retval = false;

			if (mychecksum == Checksum || Convert.ToBoolean(ConfigAppSettings.GetValue("simulatepayment")))
			{
				int iAmountPaid = Convert.ToInt32(AmountPaid);
				int iAmountDue = Convert.ToInt32(AmountDue);

				if (iAmountPaid >= iAmountDue)
				{
					retval = true;
				}

				if (iAmountPaid != iAmountDue)
				{
					logger.Warn("Bankwire transaction {0}: Amount paid unequal to amount due: {1}, {2}", this.transactionId, iAmountPaid, iAmountDue);

					MailClient.Queue(new EMail
					{
						Name = "bankwirewrongamount",
						Recipients = "administrator@gollie.nl",
						Args = new Dictionary<string, string>()
						{
											{ "{transactionid}", this.transactionId },
											{ "{amountpaid}", AmountPaid },
											{ "{amountdue}", AmountDue },
										    
						}
					});
				}
			}
			else
			{
				logger.Error("Baknwire checksum failed: transaction {0}, checksum received {1}, checksum expected {2}", this.transactionId, this.Checksum, mychecksum); 
			}

			return retval;
		}

		public string Kenmerk { get; private set; }
		public string Rtlo { get; private set; }
		public string AmountDue { get; private set; }
		public string AmountPaid { get; private set; }
		public string Checksum { get; private set; }
	}
}